package cn.ivicar.oss.controller;

import cn.com.carsmart.exception.CarsmartException;
import cn.com.carsmart.ws.ibatis.model.BaseExample;
import cn.com.carsmart.ws.service.OssUserManager;
import cn.ivicar.oss.entity.ResponseEntity;
import cn.ivicar.redis.JedisClusterFactory;
import com.google.inject.Inject;
import org.apache.commons.lang.StringUtils;
import redis.clients.jedis.JedisCluster;

import java.util.Date;

/**
 * @Author: Administrator
 * @Description:登录逻辑控制层
 * @Date: Created in 2017/5/16
 */
public class LoginController {

    @Inject
    private OssUserManager ossUserManager;

    /*
    判断是否已经登录
     */
    public boolean isLogin(String sessionId) throws CarsmartException {

        JedisCluster cluster = JedisClusterFactory.getDefaultJedisCluster();
        if ((cluster.get(sessionId) != null) && "0".equalsIgnoreCase(cluster.get(sessionId))) {
            cluster.expire(sessionId, 1800);
            return true;
        } else {
            return false;
        }
    }

    /*
    用户登录逻辑
     */
    public ResponseEntity login(String userName, String password) throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();
        //用户名为空
        if (StringUtils.isBlank(userName)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("登录失败！用户名不能为空！");
            return responseEntity;
        }
        //密码为空
        if (StringUtils.isBlank(password)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("登录失败！密码不能为空！");
            return responseEntity;
        }

        BaseExample example = this.ossUserManager.getExample();
        example.or().andPropertyEqualTo(userName, "userName").andPropertyEqualTo(password, "password");
        int i = this.ossUserManager.countByExample(example);//判断用户名密码是否匹配
        //匹配成功，redis中保存sessionId
        if (i != 0) {
            new Date().getTime();
            String sessionId = userName + "_" + String.valueOf(new Date().getTime());
            JedisCluster cluster = JedisClusterFactory.getDefaultJedisCluster();
            cluster.setex(sessionId,1800,"0");
            responseEntity.setDataObject(sessionId);
            return responseEntity;
        }else {
            responseEntity.setCode(400);
            responseEntity.setMessage("登录失败！用户名与密码不匹配！");
            return responseEntity;//匹配失败
        }

    }

}
